package com.example.myfirst.controller;

import com.example.myfirst.dto.OrderDto;
import com.example.myfirst.entity.Orders;
import com.example.myfirst.entity.ShopCart;
import com.example.myfirst.service.OrdersService;
import com.example.myfirst.service.ShopCartService;
import com.example.myfirst.utils.DateFormatUtils;
import com.example.myfirst.utils.JsonConvertUtils;
import com.example.myfirst.vo.ResultVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/orders")
@CrossOrigin
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ShopCartService shopCartService;

    @ApiOperation("生成订单")
    @GetMapping("/add")
    public void addOrder(HttpSession session, HttpServletResponse resp) throws IOException {
        OrderDto od = (OrderDto) session.getAttribute("od");
        Orders orders = new Orders();
        orders.setOrderId(od.getOrderNo());
        orders.setUserId(od.getUserId());
        orders.setTotalPrice(od.getTotalPrice());
        // 给下单时间赋值 -> 将当前时间格式化后赋值
        orders.setCreateTime(DateFormatUtils.formatDate());

        // products 该购物车中所有商品信息
        List<ShopCart> shopCartList = shopCartService.queryShopCartByUidAndIds(od.getUserId(), od.getIds());

        // 将购物车中勾选的商品数据转换为字符串
        orders.setGoods(JsonConvertUtils.objectToJson(shopCartList));
        Boolean b = ordersService.addOrders(orders);
        if (b) {
            // 订单生成成功
            session.removeAttribute("od");
            // 清空购物车
            Boolean flag = shopCartService.delShopCartBatch(od.getUserId(), od.getIds());
            if (flag) {
                // 删除成功 -> 跳转商城首页
                resp.sendRedirect("http://fanxulun.cn/#/home");
            }
        }
    }

    @ApiOperation("根据用户id获取订单信息")
    @GetMapping("/getUserOrder")
    public ResultVo queryOrders(@RequestParam Integer userId) throws JsonProcessingException {
        List<Orders> ordersList = ordersService.queryOrders(userId);
        return new ResultVo(ordersList);
    }
}
